import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    title: ['编号', '书籍名称', '出版日期', '价格', '数量', '操作'],
    bookList: [
      { id: 1, name: '三国演义', date: '2006-9', price: 100, num: 11 },
      { id: 2, name: '水浒传', date: '2020-5', price: 50, num: 12 },
      { id: 3, name: '西游记', date: '2008-12', price: 200, num: 21 },
      { id: 4, name: '红楼梦', date: '1999-9', price: 150, num: 1 }
    ],
  },
  getters: {
    allprice(state) {
      return state.bookList.reduce((binding, value) => {
        return binding += value.price * value.num
      }, 0)
    },
  },
  mutations: {
    ADD(state, index) {
      state.bookList[index].num += 1
    },
    JIAN(state, index) {
      state.bookList[index].num -= 1
    },
    remove(state, index) {
      state.bookList.splice(index, 1)
    }
  },
  actions: {
    add(context, index) {
      if (context.state.bookList[index].num) {
        context.commit('ADD', index)
      } else {
        context.state.bookList[index].num = 1
        return
      }
    },
    jian(context, index) {
      if (context.state.bookList[index].num) {
        context.commit('JIAN', index)
      } else {
        return
      }
    }
  },
  modules: {
  }
})
